<template>
    <div class="search-history">
        <van-list :error="error" error-text="加载失败，请点击重试" v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
            <van-cell v-for="item in list" :key="item.art_id" :title="item.title" />
        </van-list>
    </div>
</template>

<script>
import { ref } from 'vue'
import { getSearchResultAPI } from '@/api/search'
export default {
  name: 'searchResult',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  setup (props) {
    const list = ref([])
    const loading = ref(false)
    const finished = ref(false)
    const page = ref(1)
    const error = ref(false)
    const onLoad = async () => {
      try {
        // 请求获取数据
        const { data } = await getSearchResultAPI({
          page: page.value, // 页码
          per_page: 10, // 每页数量
          q: props.searchText// 关键字
        })
        // 将数据添加到数组中
        const { results } = data.data
        list.value.push(...results)
        // 将本次加载中loading关闭
        loading.value = false
        // 判断是否还有数据 如果有，则更新获取下一组 如果没有，则加载状态finished设置为结束
        if (results.length) {
          page.value++
        } else {
          finished.value = true
        }
      } catch (err) {
        console.log(err)
        error.value = true
        loading.value = false
      }
    }

    return {
      list,
      onLoad,
      loading,
      finished,
      error
    }
  }
}
</script>

<style scoped lang="less">

</style>
